//
//  ItemsController.m
//  GroceryStoryboards
//
//  Created by Jose Luis Lopez Redondo on 16/03/14.
//  Copyright (c) 2014 Jose Luis Lopez. All rights reserved.
//

#import "ItemsController.h"
#import "AppDelegate.h"


@implementation ItemsController

+ (NSArray *)getItems {

    NSMutableArray *items = [[NSMutableArray alloc] init];
    
    NSManagedObjectContext *context = [[AppDelegate sharedAppDelegate] managedObjectContext];
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:context];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"additionDate" ascending:NO];
    [request setSortDescriptors:@[sortDescriptor]];
    
    NSError *error;
    NSArray *tmpItems = [[context executeFetchRequest:request error:&error] mutableCopy];
    
    for(int i = 0; i < [tmpItems count]; i++) {
        Item *item = [[Item alloc] init];
        [item setItemId:[[tmpItems objectAtIndex:i] valueForKey:@"id"]];
        [item setItemName:[[tmpItems objectAtIndex:i] valueForKey:@"name"]];
        [item setItemQuantity:[[tmpItems objectAtIndex:i] valueForKey:@"quantity"]];
        [item setItemPrice:[[tmpItems objectAtIndex:i] valueForKey:@"price"]];
        [item setItemUnity:[[tmpItems objectAtIndex:i] valueForKey:@"unity"]];
        [item setItemAdditionDate:[[tmpItems objectAtIndex:i] valueForKey:@"additionDate"]];
        
        [items addObject:item];
    }
    
    // This is done so we know the array is sorted from older to newer
//    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"additionDate" ascending:YES];
//    items = [NSMutableArray arrayWithArray:[items sortedArrayUsingDescriptors:@[sort]]];
    
    return items;
}

+ (void)deleteItem:(Item *)item {
    
    NSManagedObjectContext *context = [[AppDelegate sharedAppDelegate] managedObjectContext];
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:context];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id MATCHES %@", item.itemId];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    [request setPredicate:predicate];
    
    NSError *error;
    NSArray *tmpItems = [[context executeFetchRequest:request error:&error] mutableCopy];
    
    if([tmpItems count] > 0) {
        for (NSManagedObject *item in tmpItems) {
            [context deleteObject:item];
        }
    }
    
    if (![context save:&error]) {
        NSLog(@"Error, couldn't delete: %@", [error localizedDescription]);
    } else {
        NSLog(@"Item deleted");
    }
}

+ (void)upsertItem:(Item *)item {
    
    NSManagedObjectContext *context = [[AppDelegate sharedAppDelegate] managedObjectContext];
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:context];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id MATCHES %@", item.itemId];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    [request setPredicate:predicate];
    
    NSError *error;
    NSArray *tmpItems = [[context executeFetchRequest:request error:&error] mutableCopy];
    
    NSManagedObject *tmpItem;
    if([tmpItems count] > 0)
        tmpItem = [tmpItems objectAtIndex:0];
    else
        tmpItem = [NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:context];

    [tmpItem setValue:item.itemId forKey:@"id"];
    [tmpItem setValue:item.itemName forKey:@"name"];
    [tmpItem setValue:item.itemQuantity forKey:@"quantity"];
    [tmpItem setValue:item.itemPrice forKey:@"price"];
    [tmpItem setValue:item.itemUnity forKey:@"unity"];
    [tmpItem setValue:item.itemAdditionDate forKey:@"additionDate"];
    
    
    if (![context save:&error]) {
        NSLog(@"Error, couldn't upsert: %@", [error localizedDescription]);
    } else {
        NSLog(@"Item upserted");
    }
}

@end
